// 引入模块  
var {src, dest, watch, series, parallel} = require("gulp");
var uglify = require("gulp-uglify");
var babel = require("gulp-babel");
var cssClean = require("gulp-clean-css");
var autoprefixer = require("gulp-autoprefixer");
const htmlmin = require("gulp-htmlmin");
var imagemin = require("gulp-imagemin");
const scss = require('gulp-sass')(require('sass'));
var sourcemaps = require('gulp-sourcemaps');
var webserver = require("gulp-webserver");
// 处理JS的任务
function doJS() {
    return src("./src/js/*.js")
    .pipe(sourcemaps.init())
    .pipe(babel({
        presets: ["@babel/env"]
    }))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(dest("./dist/js"))
}
 
// 处理css的任务
function doCSS() {
    return src("./src/css/*.scss")
    .pipe(scss())
    .pipe(autoprefixer({  
        overrideBrowserslist: ['last 2 versions']
    }))
    .pipe(cssClean())
    .pipe(dest('./dist/css/'))
}

// 处理HTML
function doHTML() {
    return src("./src/**/*.html")
    .pipe(htmlmin({
        collapseWhitespace: true,
        minifyCSS: true,
        minifyJS: true
    }))
    .pipe(dest('./dist/'))
}

// 处理图片
function doIMGS() {
    return src('./src/imgs/*.*')
    .pipe(imagemin())
    .pipe(dest('./dist/imgs/'))
}

// 处理libs
function doLibs() {
    return src("./src/libs/**/*.*")
    .pipe(dest("./dist/libs"))
}

var doAll = parallel([doJS, doCSS, doHTML, doIMGS, doLibs])

function doWatch() {
    return watch("./src", doAll)
}

// 定义一个启动服务器的任务
function doServer() {
    // src此时决定的是服务器的根目录
    return src("./dist")
    .pipe(webserver({
        // port 使用哪个端口
        port: 4000,
        // host 主机名
        host: 'localhost',
        // open决定默认打开哪个页面
        open: '/index.html',
        // 热更新 
        livereload: true,
        // 配置转发请求的功能 这个功能叫做代理
        proxies: [
            {
                source: "/lession01",
                target: "http://localhost:3000/lession01"
            },
            {
                source: "/lession05",
                target: "http://localhost:3000/lession05"
            },
        ]
    }))
}
 
// 小问题：如果一旦出了错我们不知道是那一条代码出的错
module.exports.doJS = doJS;
module.exports.doCSS = doCSS;
module.exports.doHTML = doHTML;
module.exports.doIMGS = doIMGS;
module.exports.doAll = doAll
module.exports.doWatch = doWatch;
module.exports.doServer = doServer;